export default {
  namespaced: true, // 命名空间
  state: {
    cartList: uni.getStorageSync('cartList') || [] // 购物车数组
  },
  getters: {
    // @param{*} state,@returns
    // 获取购物车商品总数
    getTotal (state) {
      return state.cartList.reduce((pid, item) => pid + item.goods_number, 0)
    },
    // 获取购物车列表
    getCartList (state) {
      return state.cartList
    },
    // 获取选中的商品数
    getSelectTotal (state) {
      return state.cartList
        .filter(item => item.goods_state)
        .reduce((pid, item) => pid + item.goods_number, 0)
    },
    // 获取选中的商品价格
    getSelectAmount (state) {
      return state.cartList
        .filter(item => item.goods_state)
        .reduce((pid, item) => pid + item.goods_number * item.goods_price, 0)
        .toFixed(2)
    }
  },
  mutations: {
    addToCart (state, goods) {
      const findGoods = state.cartList.find(
        item => item.goods_id === goods.goods_id
      )
      if (findGoods) {
        // 找到了，之前存在相同的商品
        findGoods.goods_number += goods.goods_number
      } else {
        // 没找到
        state.cartList.push(goods)
      }
      // 保存到本地
      uni.setStorageSync('cartList', state.cartList)
    },
    // 选中状态的改变
    updateGoodsState (state, goods) {
      const findGoods = state.cartList.find(
        item => item.goods_id === goods.goods_id
      )
      if (findGoods) {
        // 找到了，把状态改为传递过来的状态
        findGoods.goods_state = goods.goods_state
      }
      uni.setStorageSync('cartList', state.cartList)
    },
    // 数量的改变
    updateGoodNum (state, goods) {
      const findGoods = state.cartList.find(
        item => item.goods_id === goods.goods_id
      )
      if (findGoods) {
        // 找到了，把数量改为传递过来的数量
        findGoods.goods_number = goods.goods_number
      }
      uni.setStorageSync('cartList', state.cartList)
    },
    // 删除商品项
    deleteGoods (state, goods_id) {
      const findIndex = state.cartList.findIndex(
        item => item.goods_id === goods_id
      )
      if (findIndex > -1) {
        state.cartList.splice(findIndex, 1)
      }

      // 保存到本地
      uni.setStorageSync('cartList', state.cartList)
    },
    // 设置所有商品选中状态
    updateAllGoodState (state, goods_state) {
      state.cartList.forEach(item => (item.goods_state = goods_state))
      uni.setStorageSync('cartList', state.cartList)
    }
  }
}
